<?php

$device_product_ids = [
    ["K1adoeNvgJyI", "aMEgdtuXlB68"],
    ["K1Ae7ifSUYQ6", "qOMyoKdc3flG"],
];
for ($i = 0; $i < 6; $i++) {
    $data[] = [
        'id' => generateRandomCode(20),
        'name' => generateRandomCode(5),
        'org_id' => 2,
        'owner' => 'doumingquan',
        'device_id' => $device_product_ids[rand(0, 1)][0],
        'product_id' => $device_product_ids[rand(0, 1)][1],
        'type' => '高温预警',
        'level' => 'MAJOR',
        'state' => '0',
        'details' => '{"humidity":43.6,"temperature":18.6,"ts":"2024-05-10 11:16:38.617"}',
        'time' => date('Y-m-d H:i:s')
    ];
}
//var_dump($data);die();
$host = '192.168.50.67';
$dbname = 'dim5_iot';
$userName = 'root';
$password = '123456';
$pdo = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $userName, $password, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
    // 其他 PDO 属性...
]);
try {
    // PDO 连接数据库
    // $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'root', [
    //     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    //     PDO::ATTR_EMULATE_PREPARES => false,
    //     // 其他 PDO 属性...
    // ]);

    // 准备 SQL 语句（对于单条插入）
    $sql = "INSERT INTO device_alarms (id,name,org_id,owner,device_id,product_id,type,level,state,details,time) VALUES (?,?,?,?,?,?,?,?,?,?,?)";

    // 使用事务确保批量操作的一致性
    $pdo->beginTransaction();

    // 准备预处理语句
    $stmt = $pdo->prepare($sql);

    // 批量绑定并执行
    $chunkSize = 1000; // 你可以根据需要调整这个值
    $chunkCount = ceil(count($data) / $chunkSize);

    for ($i = 0; $i < $chunkCount; $i++) {
        $offset = $i * $chunkSize;
        $chunk = array_slice($data, $offset, $chunkSize);

        foreach ($chunk as $row) {
            $stmt->execute([$row["id"], $row["name"], $row["org_id"], $row["owner"], $row["device_id"], $row["product_id"], $row["type"], $row["level"], $row["state"], $row["details"], $row["time"]]);
        }
    }

    // 提交事务
    $pdo->commit();
    echo "批量插入完成！";
} catch (PDOException $e) {
    // 如果发生异常，回滚事务
    $pdo->rollBack();

    // 输出错误信息
    echo "批量插入失败: " . $e->getMessage();
}

function generateRandomCode($length = 12)
{
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $code .= 'abcdefghijklmnopqrstuvwxyz';
    $code .= '0123456789';

    // 将字符串打乱，创建一个包含所有可能字符的数组
    $shuffledCode = str_shuffle($code);

    // 从打乱后的字符串中取出前$length位字符作为随机码
    $randomCode = substr($shuffledCode, 0, $length);

    return $randomCode;
}